package com.msy;

import com.msy.generated.Greeter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.ipc.WindowsIpcService;
import org.web3j.tx.Transfer;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @ClassName Application
 * @Description TODO
 * @Author 13683
 * @Date 2019/8/13 9:47
 * @Version 1.0
 **/
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) throws Exception {
        //新建web3j客户端，默认连接 "localhost:8545"
        Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));


        System.out.println(web3j.ethAccounts().flowable().blockingFirst().getAccounts());

        log.info("Connected to Ethereum client version: "
                + web3j.web3ClientVersion().send().getWeb3ClientVersion());

        // 加载以太坊钱包文件
        Credentials credentials = WalletUtils.loadCredentials("", "D:/Geth/data0/keystore/UTC--2019-08-13T01-23-18.467473100Z--0b1db9ef3f54504a93d48ef966712f30f64105c3");

        log.info("发起一笔转账交易");
        //发起一笔转账交易
        TransactionReceipt transferReceipt = Transfer.sendFunds(
                web3j, credentials,
                "0xB421f112a974765836934Eaac5b10757b70A7240",  // you can put any address here
                BigDecimal.ONE, Convert.Unit.ETHER)  // 1 wei = 10^-18 Ether
                .send();

        /**
         * 1.solc编译智能合约     $ solc <contract>.sol --bin --abi --optimize -o <output-dir>/
         * 2.web3j 将编译后的文件打包成java代码     web3j solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name
         * 3.新建/部署智能合约
         * 4.客户端跟智能合约交互
         */

        ContractGasProvider contractGasProvider = new DefaultGasProvider();
        //新建、部署智能合约
        /*Greeter contract = Greeter.deploy(web3j, credentials, contractGasProvider, "lwl").send();*/

        //使用一个现有的智能合约
        Greeter contract = Greeter.load("0x8820DD1D14B0E79dc3B65357d3aC2Fd396Db58c0",web3j,credentials,contractGasProvider);

        // Lets modify the value in our smart contract
        CompletableFuture<TransactionReceipt> transactionReceipt = contract.newGreeting("Well hello again").sendAsync();

        transactionReceipt.thenAccept(transactionReceipt1 -> {
            System.out.println(transactionReceipt1.toString());
        });

//        for (Greeter.ModifiedEventResponse event:contract.getModifiedEvents(transactionReceipt)) {
//            log.info("Modify event fired, previous value: " + event.oldGreeting
//                    + ", new value: " + event.newGreeting);
//            log.info("Indexed event previous value: " + Numeric.toHexString(event.oldGreetingIdx)
//                    + ", new value: " + Numeric.toHexString(event.newGreetingIdx));
//        }

        //与智能合约的交互
        String contractAddress = contract.getContractAddress();

        log.info("智能合约地址：" + contractAddress);

        //当不需要Web3j实例时，需要调用shutdown方法来释放它所使用的资源.
//        web3j.shutdown();
    }
}
